package com.example.demo.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.example.demo.R;


/**
 * Created by xtxiaolu on 2021/10/9.
 * 通用对话框
 */
public class MyDialog {

    private Context context;
    private AlertDialog.Builder builder;
    private View dialogView;
    private TextView titleTextView;
    private TextView messageTextView;
    private TextView positiveButton;
    private TextView negativeButton;
    private AlertDialog alertDialog;

    public MyDialog(Context context) {
        this.context = context;
        builder = new AlertDialog.Builder(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        dialogView = inflater.inflate(R.layout.custom_dialog_layout, null);
        titleTextView = dialogView.findViewById(R.id.dialog_title);
        messageTextView = dialogView.findViewById(R.id.dialog_message);
        positiveButton = dialogView.findViewById(R.id.dialog_positive_button);
        negativeButton = dialogView.findViewById(R.id.dialog_negative_button);
        builder.setView(dialogView);
    }

    public MyDialog setTitle(String title) {
        titleTextView.setText(title);
        return this;
    }

    public MyDialog setMsg(String message) {
        messageTextView.setText(message);
        return this;
    }

    public MyDialog setPositiveButton(int textResId, final View.OnClickListener listener) {
        positiveButton.setText(context.getResources().getString(textResId));
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                if (listener != null) {
                    listener.onClick(v);
                }
            }
        });
        return this;
    }

    public MyDialog setNegativeButton(int textResId, final DialogInterface.OnClickListener listener) {
        negativeButton.setText(context.getResources().getString(textResId));
        negativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                if (listener != null) {
                    listener.onClick(null, DialogInterface.BUTTON_NEGATIVE);
                }
            }
        });
        return this;
    }

    public void show() {
        alertDialog = builder.create();
        alertDialog.show();
    }
}